############# ########### ####### ##### ### ##
#
# Copyright (C) 2010 The Hursk Group, LLC
#
# This program is free software: you can redistribute it and/or modify 
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program (See file named COPYING).  If not, see 
# <http://www.gnu.org/licenses/>.
# 
############# ########### ####### ##### ### ##

#!/usr/bin/perl -w
use strict;
use File::Find;
use File::Basename;
use Archive::Extract;
use Cwd;
my $USAGE = 'perl recursive_archive_extraction.pl (place in top dir into which you want to recurse downwards/depthwise from, including that dir)';

if (exists($ARGV[0])){warn $USAGE; exit}

push my @directories_to_search, cwd();

for (my $i=0; $i < 25; $i++){
    find(\&wanted, @directories_to_search);
}

sub wanted {
    my $file = $File::Find::name;
    return if (-d $File::Find::name or not -f $File::Find::name or $File::Find::name =~ /recursive_archive_extraction\.pl/);
    return unless ($File::Find::name =~ /\.tgz$|\.tar$|\.tar\.gz$|\.zip$|\.bz2$|\.tbz$|\.tar\.bz2$/);
    ### build an Archive::Extract object ###
    my $ae = Archive::Extract->new( archive => $File::Find::name );
    print STDERR "Unarchiving ".$File::Find::name." \n";
    ### extract to cwd() ###
    my $cwd = $File::Find::dir; $cwd .= '/' unless ($cwd =~ /\/$/);
    my $filename = fileparse($_, ('.tgz','.tar','.tar.gz','.zip','.bz2','.tbz','.tarbz2'));
    if(not -d $cwd.$filename){
        mkdir $cwd.$filename or die "Could not mkdir $cwd".$filename;
    }
    {   no warnings;
        eval {
            my $ok = $ae->extract(to => $cwd.$filename);
        };
    }
    

    unlink $File::Find::name or die "Could not delete ".$File::Find::name;
}


